import {defineStore} from 'pinia'
import {computed, ref} from 'vue'
import {getCurrentUser, login as loginApi} from '@/api/auth'
import {
    deleteUser as deleteUserApi,
    getUserDetail as getUserDetailApi,
    getUserList as getUserListApi,
    updateUserStatus as updateUserStatusApi
} from '@/api/user'

/**
 * 用户状态管理
 * 包含登录认证和用户管理功能
 */
export const useUserStore = defineStore('user', () => {
    // 认证相关状态
    const token = ref(localStorage.getItem('admin_token') || '')
    const userInfo = ref(null)
    const isLoading = ref(false)

    // 用户管理相关状态
    const users = ref([])
    const currentUser = ref(null)
    const userStatistics = ref(null)
    const loading = ref(false)
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)

    // 用户状态映射
    const userStatusMap = {
        0: {text: '禁用', type: 'danger'},
        1: {text: '正常', type: 'success'}
    }

    // 性别映射
    const genderMap = {
        0: {text: '未知', icon: 'Question'},
        1: {text: '男', icon: 'Male'},
        2: {text: '女', icon: 'Female'}
    }

    // 计算属性
    const userCount = computed(() => users.value.length)
    const hasUsers = computed(() => users.value.length > 0)

    /**
     * 登录
     * @param {Object} loginForm - 登录表单数据
     * @param {string} loginForm.username - 用户名
     * @param {string} loginForm.password - 密码
     */
    const login = async (loginForm) => {
        try {
            isLoading.value = true

            // 调用登录API
            const response = await loginApi(loginForm)
            const {token: authToken, user} = response.data

            // 保存token和用户信息
            token.value = authToken
            userInfo.value = user

            // 持久化存储token
            localStorage.setItem('admin_token', authToken)

            return {success: true, data: response.data}
        } catch (error) {
            console.error('登录失败:', error)
            return {
                success: false,
                message: error.response?.data?.message || '登录失败，请重试'
            }
        } finally {
            isLoading.value = false
        }
    }

    /**
     * 登出
     */
    const logout = () => {
        // 清除状态
        token.value = ''
        userInfo.value = null

        // 清除本地存储
        localStorage.removeItem('admin_token')
    }

    /**
     * 获取当前用户信息
     */
    const fetchUserInfo = async () => {
        try {
            if (!token.value) {
                return {success: false, message: '未登录'}
            }

            const response = await getCurrentUser()
            userInfo.value = response.data

            return {success: true, data: response.data}
        } catch (error) {
            console.error('获取用户信息失败:', error)

            // 如果token无效，清除登录状态
            if (error.response?.status === 401) {
                logout()
            }

            return {
                success: false,
                message: error.response?.data?.message || '获取用户信息失败'
            }
        }
    }

    /**
     * 检查是否已登录
     */
    const isLoggedIn = () => {
        return !!token.value
    }

    /**
     * 获取用户显示名称
     */
    const getDisplayName = () => {
        if (!userInfo.value) return '未知用户'
        return userInfo.value.nickname || userInfo.value.username || '未知用户'
    }

    /**
     * 检查是否为管理员
     * 根据用户名判断（admin为管理员）
     */
    const isAdmin = () => {
        if (!userInfo.value) return false
        return userInfo.value.username === 'admin'
    }

    /**
     * 获取用户列表（管理端）
     * @param {Object} params 查询参数
     */
    const getUserList = async (params = {}) => {
        loading.value = true
        try {
            const response = await getUserListApi({
                current: currentPage.value,
                size: pageSize.value,
                ...params
            })

            if (response.data) {
                users.value = response.data.records || []
                total.value = response.data.total || 0
                currentPage.value = response.data.current || 1
            }

            return response
        } catch (error) {
            console.error('获取用户列表失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 获取用户详情（管理端）
     * @param {number} id 用户ID
     */
    const getUserDetail = async (id) => {
        loading.value = true
        try {
            const response = await getUserDetailApi(id)
            if (response.data) {
                currentUser.value = response.data
            }
            return response
        } catch (error) {
            console.error('获取用户详情失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 更新用户状态（管理端）
     * @param {number} id 用户ID
     * @param {number} status 状态值
     */
    const updateUserStatus = async (id, status) => {
        loading.value = true
        try {
            const response = await updateUserStatusApi(id, status)
            // 更新成功后刷新列表
            await getUserList()
            return response
        } catch (error) {
            console.error('更新用户状态失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 删除用户（管理端）
     * @param {number} id 用户ID
     */
    const deleteUser = async (id) => {
        loading.value = true
        try {
            const response = await deleteUserApi(id)
            // 删除成功后刷新列表
            await getUserList()
            return response
        } catch (error) {
            console.error('删除用户失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 获取用户统计信息（管理端）
     */
    const getUserStatistics = async () => {
        loading.value = true
        try {
            const response = await request.get('/admin/users/statistics')
            if (response.data) {
                userStatistics.value = response.data
            }
            return response
        } catch (error) {
            console.error('获取用户统计失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 设置分页参数
     * @param {number} page 页码
     * @param {number} size 每页大小
     */
    const setPagination = (page, size) => {
        currentPage.value = page
        pageSize.value = size
    }

    /**
     * 获取用户状态显示信息
     * @param {number} status 状态值
     */
    const getUserStatusInfo = (status) => {
        return userStatusMap[status] || {text: '未知', type: 'info'}
    }

    /**
     * 获取性别显示信息
     * @param {number} gender 性别值
     */
    const getGenderInfo = (gender) => {
        return genderMap[gender] || {text: '未知', icon: 'Question'}
    }

    /**
     * 重置管理状态
     */
    const resetManagementState = () => {
        users.value = []
        currentUser.value = null
        userStatistics.value = null
        loading.value = false
        total.value = 0
        currentPage.value = 1
        pageSize.value = 10
    }

    // 返回状态和方法
    return {
        // 认证状态
        token,
        userInfo,
        isLoading,

        // 管理状态
        users,
        currentUser,
        userStatistics,
        loading,
        total,
        currentPage,
        pageSize,

        // 计算属性
        userCount,
        hasUsers,

        // 认证方法
        login,
        logout,
        fetchUserInfo,
        isLoggedIn,
        getDisplayName,
        isAdmin,

        // 管理方法
        getUserList,
        getUserDetail,
        updateUserStatus,
        deleteUser,
        getUserStatistics,
        setPagination,
        getUserStatusInfo,
        getGenderInfo,
        resetManagementState
    }
})
